/**
 * Description
 *
 * Creation Date 25/10/2017
 * @author Candy
 */
import BaseComponent from '../../prototype/baseComponent'
import CartModel from '../../models/v1/cart'
import AddressModel from '../../models/v1/address'
import formidable from 'formidable'
import dtime from 'time-formater'

class Cart extends  BaseComponent {
    constructor() {
        super()
        this.checkout = this.checkout.bind(this)
        this.extra = [{
            description: '',
            name: '运费',
            price: 10
        }]
    }
    async checkout(req, res, next) {
        const UID = req.session.user_id
        const QID = req.query.user_id
        const user_id = UID || QID
        const form = new formidable.IncomingForm()
        form.parse(req, async(err, fields, files) => {
            const {entities = []} = fields
            try {
                if(!(entities instanceof Array) || !entities.length) {
                    throw new Error('entities参数错误')
                }
            } catch(err) {
                console.log(err);
                res.send({
                    status: 0,
                    type: 'ERROR_PARAMS',
                    message: err.message
                })
                return
            }
            let payments;
            let cart_id;
            let checkout_time;
            let address;
            try {
                payments = [{ is_online_payment: false }]
                cart_id = await this.getId('cart_id')
                checkout_time = dtime().format('YYYY-MM-DD HH:mm')
                address = await AddressModel.findOne({user_id, is_active: true}, '-_id')
            } catch(err) {
                console.log('获取数据数据失败', err);
                res.send({
                    status: 0,
                    type: 'ERROR_DATA',
                    message: '添加购物车失败',
                })
                return
            }
            let proPrice = 0
            entities.forEach(item => {
                proPrice += item.price * item.quantity
            })
            const totalPrice = proPrice + this.extra[0].price
            const checkoutInfo = {
                user_id,
                cart_id,
                cart: {
                    groups: entities,
                    extras: this.extra,
                    total_price: totalPrice,
                    payments,
                    address,
                    time: checkout_time
                }
            }
            try {
                const newCart = new CartModel(checkoutInfo)
                const cart = await newCart.save()
                res.send(cart)
            } catch (err) {
                console.log('保存购物车数据失败');
                res.send({
                    status: 0,
                    type: 'ERROR_TO_SAVE_CART',
                    message: '加入购物车失败'
                })
            }
        })
    }
    async getCartById(req, res, next) {
        const {cart_id, user_id} = req.query
        try {
            const cartInfo = await CartModel.findOne({cart_id, user_id}, '-_id')
            res.send(cartInfo)
        } catch(err) {
            console.log('获取购物车信息失败', err)
            res.send({
                status: 0,
                type: 'ERROR_GET_CART_INFO',
                message: '获取购物车信息失败'
            })
        }
    }
    async getCarts(req, res, next) {
        const {cart_id, user_id} = req.query
        try {
            const cartInfo = await CartModel.find({user_id, cart_id:{$ne :cart_id}}, '-_id')
            res.send(cartInfo)
        } catch(err) {
            console.log('获取购物车信息失败', err)
            res.send({
                status: 0,
                type: 'ERROR_GET_CART_INFO',
                message: '获取购物车信息失败'
            })
        }
    }
    async deleteCart(req, res, next) {
        const {cart_id, user_id} = req.query
        try {
            await CartModel.findOneAndRemove({user_id, cart_id}, '-_id')
            res.send({
                status: 1,
                message: 'Delete Cart successful'
            })
        } catch(err) {
            console.log('Delete Cart fail', err)
            res.send({
                status: 0,
                type: 'ERROR_DELETE_CART_INFO',
                message: 'Delete Cart fail'
            })
        }
    }
}

export default new Cart()